package org.example.rzfx.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

/**
 * Netty日志接收服务器
 */
@Component
@Slf4j
public class NettyLogServer implements CommandLineRunner {
    
    @Value("${netty.log.server.port:9999}")
    private int port;
    
    @Resource
    private NettyLogHandler nettyLogHandler;
    
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    
    @Override
    public void run(String... args) throws Exception {
        start();
    }
    
    /**
     * 启动Netty服务器
     */
    public void start() throws InterruptedException {
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
        
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        // 添加字符串编解码器
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new StringEncoder());
                        // 添加业务处理器
                        pipeline.addLast(nettyLogHandler);
                    }
                });
            
            // 绑定端口，开始接收连接
            ChannelFuture future = bootstrap.bind(port).sync();
            log.info("Netty日志接收服务器启动成功，监听端口: {}", port);
            
            // 不要在这里调用 future.channel().closeFuture().sync()
            // 因为这会阻塞主线程，导致Spring Boot无法正常启动
            
        } catch (Exception e) {
            log.error("Netty服务器启动失败", e);
            shutdown();
        }
    }
    
    /**
     * 关闭服务器
     */
    public void shutdown() {
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        log.info("Netty日志接收服务器已关闭");
    }
}

